package com.way.filemanager.navigation;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;

import hwdroid.dialog.AlertDialog;
import hwdroid.dialog.Dialog;
import hwdroid.dialog.DialogInterface;
import hwdroid.dialog.DialogInterface.OnCancelListener;
import hwdroid.dialog.ProgressDialog;
import hwdroid.util.DialogUtils;
import hwdroid.widget.ActionBar.ActionBarView;
import hwdroid.widget.ActionBar.ActionBarView.OnBackKeyItemClick;
import hwdroid.widget.FooterBar.FooterBarButton;
import hwdroid.widget.FooterBar.FooterBarItem;
import hwdroid.widget.FooterBar.FooterBarMenu;
import hwdroid.widget.FooterBar.FooterBarType.OnFooterItemClick;



import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.way.filemanager.FileManagerAppFrame;
import com.way.filemanager.R;
import com.way.filemanager.fragment.activity2frag_if;
import com.way.filemanager.model.FileSystemObject;
import com.way.filemanager.navigation.MyAdapter.SearchCancel;
import com.way.filemanager.navigation.MyFileManager.FileChangeListener;
import com.way.filemanager.navigation.MyFileManager.FileListener;
import com.way.filemanager.navigation.MyFileManager.FileOrder;
import com.way.filemanager.navigation.MyFileManager.FileProgressListener;
import com.way.filemanager.ui.dialogs.CustomProgressDialog;
import com.way.filemanager.util.AndroidHelper;
import com.way.filemanager.util.CommonFunc;
import com.way.filemanager.util.CommonIdDef;
import com.way.filemanager.util.DialogHelper;
import com.way.filemanager.util.FileCrushDialog;
import com.way.filemanager.util.FileDetailDialog;
import com.way.filemanager.util.FileHelper;
import com.way.filemanager.util.FileInfo;
import com.way.filemanager.util.ScrollOverListView;
import com.way.filemanager.util.ZipDialog;

public class NavigationListFragmant extends Fragment implements activity2frag_if, FileProgressListener, FileChangeListener
{
    private final static int MENU_ID_ORDER = 0;
    private final static int MENU_ID_COPY = 1;
    private final static int MENU_ID_DELETE = 2;
    private final static int MENU_ID_CUT = 3;
    private final static int MENU_ID_SHARE = 4;
    private final static int MENU_ID_NEWFOLDER = 5;
    private final static int MENU_ID_SHOWHIDDEN = 6;
    private final static int MENU_ID_SELECT = 7;
    private final static int MENU_ID_CANCEL = 8;
    private final static int MENU_ID_ZIP = 9;
    private final static int SIZE = 1024;
    public enum Mode
    {
        normal, select, paste, search,getcontext
    }

    public enum SelectMode
    {
        copy, cut, delete, share, download, Unzip, crush_delete,Zip
    }


    private MyFileManager fm;
    private MyAdapter mAdapter;
    private FooterBarMenu mFooterBarMenu;
    private FooterBarButton mFooterBarButton;
    private Activity mActivity;
    private Mode mMode = Mode.normal;
    private SelectMode mSelectMode = SelectMode.copy;
    private ViewGroup mfootbar_menu_id;
    private ActionBarView mSelectView;
    private View mSearchView;
    private CustomProgressDialog mProgressDialog;
    private ProgressDialog mCancelProgressDialog;
    private SearchView mWidgetSearchView;

    private LinkedList<File> mSelectedFiles;

    private ViewGroup mDirContainer;
    private View mTagView;
    private HorizontalScrollView mTagScroll;
    private Handler mHandler = new Handler();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
        //BugID:99830:fix FragmentList size is 0 bug after change language
        ((FileManagerAppFrame)mActivity).setFragmentMap(1, this);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        mActivity = getActivity();
        ViewGroup v = (ViewGroup) inflater.inflate(R.layout.navigation_list, container, false);
        fm = MyFileManager.getFm();

        initFooterBarMenu();

        mfootbar_menu_id = (ViewGroup) v.findViewById(R.id.natigation_footbar_menu);
        mfootbar_menu_id.addView(mFooterBarMenu);

        mAdapter = new MyAdapter(mActivity, v,fm);
        fm.setFileChangeListener(mAdapter);

        mAdapter.setLongClickFileListener(longClickFile);
        mAdapter.setFileChangeListener(this);
        mAdapter.setSearchButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchMode(Mode.search, SelectMode.copy);
            }
        });

        mTagView = v.findViewById(R.id.navigation_dir_id);
        mDirContainer = (LinearLayout) v.findViewById(R.id.dir_container);
        mDirContainer.removeAllViews();
        mTagScroll = (HorizontalScrollView) v.findViewById(R.id.horizontalScrollView1);

        return v;
    }

    private void initFooterBarMenu()
    {
        if(null == mFooterBarMenu)
        {
            Resources r = mActivity.getResources();
            Drawable d = r.getDrawable(R.drawable.more_menu);
            mFooterBarMenu = new FooterBarMenu(mActivity);
            mFooterBarMenu.addItem(MENU_ID_ORDER, r.getText(R.string.actions_menu_Sort), r.getDrawable(R.drawable.sort_menu));
            mFooterBarMenu.addItem(MENU_ID_COPY, r.getText(R.string.actions_menu_Copy), r.getDrawable(R.drawable.copy_menu));
            mFooterBarMenu.addItem(MENU_ID_DELETE, r.getText(R.string.actions_menu_Delete), r.getDrawable(R.drawable.delete_menu));
            mFooterBarMenu.addItem(MENU_ID_CUT, r.getText(R.string.actions_menu_Cut), d);
            mFooterBarMenu.addItem(MENU_ID_SHARE, r.getText(R.string.actions_menu_Share), d);
            mFooterBarMenu.addItem(MENU_ID_ZIP, r.getText(R.string.actions_menu_Zip), d);
            mFooterBarMenu.addItem(MENU_ID_NEWFOLDER, r.getText(R.string.actions_menu_NewDir), d);
            mFooterBarMenu.addItem(MENU_ID_SHOWHIDDEN, fm.isShowHidden() ? r.getText(R.string.actions_menu_NotShowHideFile) : r.getText(R.string.actions_menu_ShowHideFile), d);
            mFooterBarMenu.setOnFooterItemClick(new OnFooterItemClick()
            {
                @Override
                public void onFooterItemClick(View view, int id)
                {
                    switch(id)
                    {
                        case MENU_ID_ORDER:
                            onMenuSort();
                            CommonFunc.TA_Click(CommonFunc.OnClick_Sort);
                            break;
                        case MENU_ID_COPY:
                            onMenuCopy();
                            CommonFunc.TA_Click(CommonFunc.OnClick_Copy);
                            break;
                        case MENU_ID_DELETE:
                            onMenuDelete();
                            CommonFunc.TA_Click(CommonFunc.OnClick_Delete);
                            break;
                        case MENU_ID_CUT:
                            onMenuCut();
                            CommonFunc.TA_Click(CommonFunc.OnClick_Cut);
                            break;
                        case MENU_ID_SHARE:
                            onMenuShare();
                            CommonFunc.TA_Click(CommonFunc.OnClick_Share);
                            break;
                        case MENU_ID_NEWFOLDER:
                            onMenuNewDir();
                            CommonFunc.TA_Click(CommonFunc.OnClick_New);
                            break;
                        case MENU_ID_SHOWHIDDEN:
                            onMenuShowHidden();
                            CommonFunc.TA_Click(CommonFunc.OnClick_Hide);
                            break;
                        case MENU_ID_ZIP:
                            onMenuZip();
                            break;
                        default:
                            break;
                    }
                }
            });

            mFooterBarMenu.setPrimaryItemCount(3);
            mFooterBarMenu.updateItems();
        }
    }

    private void ensureFooterButton() {
        if(null == mFooterBarButton) {
            mFooterBarButton = new FooterBarButton(mActivity);
            mFooterBarButton.setOnFooterItemClick(new OnFooterItemClick() {
                @Override
                public void onFooterItemClick(View view, int id) {
                    switch(id) {
                        case MENU_ID_SELECT:
                            onMenuSelectOk();
                            //CommonFunc.TA_Click(CommonFunc.OnClick_Paste);
                            break;
                        case MENU_ID_CANCEL:
                            onMenuSelectCancel();
                            break;
                        default:
                            break;
                    }
                }
            });

            mFooterBarButton.addItem(MENU_ID_CANCEL, mActivity.getResources().getText(R.string.cancel));
            mFooterBarButton.addItem(MENU_ID_SELECT, getResources().getText(R.string.actions_menu_Copy));
            mFooterBarButton.updateItems();
            mAdapter.setFooterBarSelectButton(mFooterBarButton.getItem(MENU_ID_SELECT));
        }
    }

    private void ensureSelectView()
    {
        if(null == mSelectView)
        {
            mSelectView = new ActionBarView(mActivity);
            /*mSelectView.showBackKey(true, new OnBackKeyItemClick()
            {
                @Override
                public void onBackKeyItemClick()
                {
                    onMenuSelectCancel();
                }
            });
            */
            mSelectView.setTitle(mActivity.getResources().getQuantityString(R.plurals.numberOfSelected, 1, 0));
            CheckBox cb = new CheckBox(mActivity);
            cb.setId(R.id.checkbox_select_all);
            mSelectView.addRightItem(cb);

            mAdapter.setActionBarView(mSelectView);
            mAdapter.setSelectAll(cb);
        }
    }

    private void ensureSearchView()
    {
        //if(null == mSearchView)
        {
            LayoutInflater mInflater = LayoutInflater.from(mActivity);
            mSearchView = mInflater.inflate(R.layout.category_search_bar, null);
            //bugid:103585
            mWidgetSearchView = (SearchView) mSearchView.findViewById(R.id.Serachbar_view);
            mWidgetSearchView.setIconified(false);
            View searchBack = mSearchView.findViewById(R.id.Searchbar_back);
            searchBack.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    //bugid:103585
                    mWidgetSearchView.clearFocus();
                    onMenuSelectCancel();
                    mAdapter.setSearchMode(false);
                }
            });

            mAdapter.setSearchView(mWidgetSearchView);
            mAdapter.setSearchCancel(new SearchCancel()
            {
                @Override
                public void cancelSearchMode() {
                    // TODO Auto-generated method stub
                    mWidgetSearchView.clearFocus();
                    onMenuSelectCancel();
                    mAdapter.setSearchMode(false);
                }
            });
            mAdapter.setSearchMode(true);
            CommonFunc.TA_Click(CommonFunc.OnClick_Search);
        }
    }

    public void onResume()
    {
        super.onResume();
        //switchMode(mMode, mSelectMode);
        fm.setFileChangeListener(mAdapter);
    }
    @Override
    public void onPause()
    {
        super.onPause();
        fm.setFileChangeListener(null);
    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        mAdapter.onDestroy();
        mAdapter = null;
    }

    @Override
    public boolean fragOnKeyUp(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            switch(mMode)
            {
                default:
                case normal:
                case paste:
                    return mAdapter.onBackPressed();
                case select:
                case search:
                    switchMode(Mode.normal, mSelectMode);
                    return true;
            }
        }
        return false;
    }

    @Override
    public boolean exit()
    {
        //fm.setFileChangeListener(null);
        return true;
    }

    private void switchMode(Mode m, SelectMode sm)
    {
        MyFileManager.log("switchMode "+m+", SelectMode "+sm);
        if((mAdapter == null)||(mTagView ==null))
            return;
        mMode = m;
        mSelectMode = sm;
        ActionBar bar = mActivity.getActionBar();
        switch(mMode)
        {
            default:
            case normal:
                ((FileManagerAppFrame)mActivity).SetCanViewPagerMove(true);
                mAdapter.setMode(m);
                mfootbar_menu_id.removeAllViews();
                mfootbar_menu_id.addView(mFooterBarMenu);
                bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
                bar.setDisplayShowTitleEnabled(false);
                bar.setDisplayShowHomeEnabled(false);
                bar.setDisplayShowCustomEnabled(false);
                mSelectedFiles = null;
                mTagView.setVisibility(View.VISIBLE);
                break;
            case select:
                ensureFooterButton();
                ((FileManagerAppFrame)mActivity).SetCanViewPagerMove(false);
                FooterBarItem s = mFooterBarButton.getItem(MENU_ID_SELECT);
                ensureSelectView();
                mAdapter.setMode(m);
                switch(mSelectMode)
                {

                    case copy:
                        s.setItemTitle(R.string.actions_menu_Copy);
                        break;
                    case cut:
                        s.setItemTitle(R.string.actions_menu_Cut);
                        break;
                    case delete:
                        s.setItemTitle(R.string.actions_menu_delete);
                        break;
                    case share:
                        s.setItemTitle(R.string.actions_menu_Share);
                        break;
                    case Zip:
                        s.setItemTitle(R.string.actions_menu_Zip);
                        break;
                    default:
                        break;
                }

                mfootbar_menu_id.removeAllViews();
                mfootbar_menu_id.addView(mFooterBarButton);
                bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
                bar.setCustomView(mSelectView);
                bar.setDisplayShowTitleEnabled(false);
                bar.setDisplayShowHomeEnabled(false);
                bar.setDisplayShowCustomEnabled(true);
                mSelectedFiles = null;
                mTagView.setVisibility(View.VISIBLE);

                break;
            case paste:
                ((FileManagerAppFrame)mActivity).SetCanViewPagerMove(true);

                ensureFooterButton();
                if(sm == SelectMode.download)
                    mFooterBarButton.getItem(MENU_ID_SELECT).setItemTitle(R.string.download);
                else if(sm == SelectMode.Unzip)
                    mFooterBarButton.getItem(MENU_ID_SELECT).setItemTitle(R.string.ali_unzip);
                else if(sm == SelectMode.Zip)
                    mFooterBarButton.getItem(MENU_ID_SELECT).setItemTitle(R.string.ali_zip);
                else
                    mFooterBarButton.getItem(MENU_ID_SELECT).setItemTitle(R.string.ali_paste);

                mAdapter.setMode(m);
                mfootbar_menu_id.removeAllViews();
                mfootbar_menu_id.addView(mFooterBarButton);
                bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
                bar.setDisplayShowTitleEnabled(false);
                bar.setDisplayShowHomeEnabled(false);
                bar.setDisplayShowCustomEnabled(false);
                mTagView.setVisibility(View.VISIBLE);
                break;
            case search:
                ((FileManagerAppFrame)mActivity).SetCanViewPagerMove(false);
                mAdapter.setMode(m);
                mfootbar_menu_id.removeAllViews();
                mfootbar_menu_id.addView(mFooterBarMenu);
                bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
                bar.setDisplayShowTitleEnabled(false);
                bar.setDisplayShowHomeEnabled(false);
                bar.setDisplayShowCustomEnabled(true);
                ensureSearchView();
                bar.setCustomView(mSearchView);
                mSelectedFiles = null;
                mTagView.setVisibility(View.VISIBLE);
                break;
        }
        onChanged();
    }



    private int mMenuSortChoice;
    private void onMenuSort()
    {
        final Activity activity = getActivity();
        Resources r = activity.getResources();

        new AlertDialog.Builder(getActivity())
        //.setTitle(R.string.actions_menu_Sort)
        .setSingleChoiceItems(new String[]{r.getString(R.string.ali_order_name)
                , r.getString(R.string.ali_order_size)
                , r.getString(R.string.ali_order_date)
                , r.getString(R.string.ali_order_type)}
                , CommonFunc.fileOrder2Index(CommonFunc.loadSaved(mActivity)), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                mMenuSortChoice = whichButton;
                fm.saveOrder(CommonFunc.index2FileOrder(mMenuSortChoice));
                dialog.dismiss();
                switch(whichButton)
                {
                    case CommonFunc.NAME_INDEX:
                        CommonFunc.TA_Click(CommonFunc.OnClick_Sort_name);
                        break;
                    case CommonFunc.SIZE_INDEX:
                        CommonFunc.TA_Click(CommonFunc.OnClick_Sort_size);
                        break;
                    case CommonFunc.DATE_INDEX:
                        CommonFunc.TA_Click(CommonFunc.OnClick_Sort_date);
                        break;
                    case CommonFunc.TYPE_INDEX:
                        CommonFunc.TA_Click(CommonFunc.OnClick_Sort_type);
                        break;
                }
            }
        })
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        })
        //.setNegativeButton(R.string.cancel, null)
       .create().show();
    }

    private void onMenuCopy()
    {
        switchMode(Mode.select, SelectMode.copy);
    }

    private void onMenuDelete()
    {
        switchMode(Mode.select, SelectMode.delete);
    }

    private void onMenuCut()
    {
        switchMode(Mode.select, SelectMode.cut);
    }

    private void onMenuShare()
    {
        switchMode(Mode.select, SelectMode.share);
    }
    private void onMenuZip()
    {
        switchMode(Mode.select, SelectMode.Zip);
    }

    private void onMenuNewDir()
    {
        LayoutInflater factory = LayoutInflater.from(mActivity);
        final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry_mkdir, null);
        final EditText editText = (EditText) textEntryView.findViewById(R.id.mkdir_edit);
        editText.setText(R.string.unnamed_folder);
        editText.setSelectAllOnFocus(true);
        /*editText.setOnFocusChangeListener(new OnFocusChangeListener(){
            @Override
            public void onFocusChange(View arg0, boolean arg1) {
                // TODO Auto-generated method stub
                ((EditText)arg0).setText(null);
                arg0.setOnFocusChangeListener(null);
            }

        });
        editText.selectAll();*/
        final String text = editText.getText().toString();
        editText.setSelection(TextUtils.isEmpty(text) ? 0 : text.length());

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
        .setTitle(R.string.input_dir_name)
        .setView(textEntryView)
        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                String newname = editText.getText().toString();
                newname = newname.trim();
                if (!newname.equalsIgnoreCase(""))
                {
                    fm.mkDir(newname);
                }
                //Bugid:103586
                else
                {
                    Toast.makeText(mActivity, R.string.ali_dirNameEmtpy, Toast.LENGTH_SHORT)
                    .show();
                }
            }
        })
        .setNegativeButton(R.string.cancel, null);
        Dialog dlg = builder.create();
        dlg.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        dlg.show();
    }

    private void onMenuShowHidden()
    {
        boolean show = fm.isShowHidden();
        show = !show;
        mFooterBarMenu.getItem(MENU_ID_SHOWHIDDEN).setItemTitle(show ? R.string.actions_menu_NotShowHideFile
                : R.string.actions_menu_ShowHideFile);
        fm.saveShowHidden(show);
        mFooterBarMenu.updateItems();
    }

    private void deleteFiles(final LinkedList<File> files)
    {
        AlertDialog.Builder builder =  new AlertDialog.Builder(mActivity);
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int whichButton)
            {
                if(!fm.doDeleteFiles(files, NavigationListFragmant.this))
                {
                    switchMode(Mode.normal, SelectMode.copy);
                }
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
            }
        });

        //View customTitleView = DialogUtils.buildCustomView(mActivity, R.string.DeleteFileWarnning);
        //builder.setCustomTitle(customTitleView);
        builder.setTitle(R.string.DeleteFileWarnning);
        AlertDialog dd = builder.create();

        dd.show();
     //DialogUtils.fromBottomToTop(dd);
    }

    private void copyFiles(LinkedList<File> files)
    {
        if(!fm.doCopyFiles(mSelectedFiles, this))
        {
            switchMode(Mode.normal, SelectMode.copy);
        }
    }

    private void cutFiles(LinkedList<File> files)
    {
        if(!fm.doCutFiles(mSelectedFiles, this))
        {
            switchMode(Mode.normal, SelectMode.copy);
        }
    }

    private void onMenuSelectOk()
    {
        if(mMode == Mode.select)
        {
            LinkedList<File> files = mAdapter.getSelectedFiles();
            if(files == null || files.size() == 0)
            {
                return;
            }

            switch(mSelectMode)
            {
                case copy:
                case cut:
                    mSelectedFiles = files;
                    switchMode(Mode.paste, mSelectMode);
                    break;
                case delete:
                    deleteFiles(files);
                    break;
                case share:
                    //do share
                    CommonFunc.shareDialog(mActivity, files);
                    CommonFunc.TA_Click(CommonFunc.LongPress_Share);
                    onMenuSelectCancel();
                    break;
                case Zip:
                    //do share
                    ZipDialog mZipDialog = new ZipDialog(mActivity, files,files.get(0).getParentFile().getPath());
                    mZipDialog.show();
                    onMenuSelectCancel();
                    break;
                default:break;
            }
        }
        else if(mMode == Mode.paste)
        {
            if(mSelectMode == SelectMode.copy)
            {
                CommonFunc.TA_Click(CommonFunc.OnClick_Paste);
                copyFiles(mSelectedFiles);
            }
            else if(mSelectMode == SelectMode.cut)
            {
                CommonFunc.TA_Click(CommonFunc.OnClick_Paste);
                cutFiles(mSelectedFiles);
            }
            else if(mSelectMode == SelectMode.download)
            {
                CommonFunc.TA_Click(CommonFunc.OnClick_Download);
                notifyDownload(true);
                switchMode(Mode.normal, SelectMode.copy);
            }
            else if(mSelectMode == SelectMode.Unzip)
            {
                notifyDownload(true);
                switchMode(Mode.normal, SelectMode.copy);
                CommonFunc.TA_Click(CommonFunc.OnClick_Unzip);
            }
            ((FileManagerAppFrame)mActivity).setOnlineSelectedMode();
        }
    }

    private void onMenuSelectCancel()
    {
        switchMode(Mode.normal, SelectMode.copy);
        ((FileManagerAppFrame)mActivity).setOnlineSelectedMode();
    }

    private void notifyDownload(boolean gotPath)
    {
        if(mListLocalListener != null)
        {
            final FileListener l = mListLocalListener;
            final File dir = gotPath ? fm.getCurrentDir() : null;
            new Thread()
            {
                @Override
                public void run()
                {
                    if(l != null)
                    {
                        l.onFile(dir);
                    }
                }
            }.start();
        }
        mListLocalListener = null;
    }

    private void showProgressDialog(SelectMode selectMode)
    {
        final int titleRes;
        switch(selectMode)
        {
            default:
            case copy:
                titleRes = R.string.dialog_title_do_copy;
                break;

            case cut:
                titleRes = R.string.dialog_title_do_cut;
                break;

            case delete:
                titleRes = R.string.dialog_title_do_delete;
                break;

            case crush_delete:
                titleRes = R.string.dialog_title_do_crush_delete;
                break;
        }

        mProgressDialog = CustomProgressDialog.create(getActivity(), getString(titleRes));
        //mProgressDialog.setTitle(titleRes);
        int Cancel_id= R.string.cancel;
        if(mSelectMode == SelectMode.crush_delete)
        {
            Cancel_id = R.string.CrushFileStop;
        }
        mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                getText(Cancel_id), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                doCancelFileProcess();
            }
        });
        mProgressDialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                doCancelFileProcess();
            }
        });
        mProgressDialog.show();
        //DialogUtils.fromBottomToTop(mProgressDialog);

    }

    @Override
    public void onPreProgressStart(SelectMode mode)
    {
        showProgressDialog(mode);
    }

    @Override
    public void onProgress(final File f, final int p, int total)
    {
        if(mProgressDialog != null || mProgressDialog.isShowing())
        {
            mProgressDialog.setMax(total);
            mProgressDialog.setProgress(p);
            mProgressDialog.setMessage(f.getAbsolutePath());
        }
    }

    @Override
    public void onProgressDone()
    {
        if(mProgressDialog != null && mProgressDialog.isShowing())
        {
            mProgressDialog.setProgress(100);
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }

        if(mCancelProgressDialog != null &&  mCancelProgressDialog.isShowing())
        {
            mCancelProgressDialog.dismiss();
            mCancelProgressDialog = null;
        }

        switchMode(Mode.normal, SelectMode.copy);
    }

    private void doCancelFileProcess()
    {
        mCancelProgressDialog = new ProgressDialog(mActivity);
        mCancelProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mCancelProgressDialog.setTitle(R.string.ali_canceling);
        mCancelProgressDialog.setMax(-1);

        mCancelProgressDialog.show();
        //DialogUtils.fromBottomToTop(mCancelProgressDialog);
        fm.cancelFileProcess();
    }

    private void showDetail(File file)
    {
        file = new File(file.getAbsolutePath());
        LayoutInflater factory = LayoutInflater.from(mActivity);
        View detailView = factory.inflate(R.layout.alert_dialog_text_entry_detail, null);

        TextView pathTextView =  (TextView)detailView.findViewById(R.id.path_context);
        TextView sizeTextView =  (TextView)detailView.findViewById(R.id.size_context);
        TextView timeTextView =  (TextView)detailView.findViewById(R.id.time_context);
        TextView readableTextView =  (TextView)detailView.findViewById(R.id.readable_context);
        TextView writeableTextView =  (TextView)detailView.findViewById(R.id.writeable_context);
        TextView hideTextView =  (TextView)detailView.findViewById(R.id.hide_context);

        pathTextView.setText(file.getAbsolutePath());
        sizeTextView.setText(CommonFunc.FormetFileSize(file.length()));
        timeTextView.setText(CommonFunc.CreateTimeFormat(file.lastModified()));
        readableTextView.setText(file.canRead() ? R.string.yes : R.string.no);
        writeableTextView.setText(file.canWrite() ? R.string.yes : R.string.no);
        hideTextView.setText(file.isHidden() ? R.string.yes : R.string.no);

        AlertDialog a = new AlertDialog.Builder(mActivity)
            .setTitle(file.getName())
            .setView(detailView)
            .setNegativeButton(R.string.ali_iknow, null).create();
        a.show();
                //DialogUtils.fromBottomToTop(a);

    }

    private void deleteUnrecovery(final File file)
    {
        AlertDialog.Builder builder =  new AlertDialog.Builder(mActivity);
        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int whichButton)
            {
                LinkedList<File> files = new LinkedList<File>();
                files.add(file);

                if(!fm.doCrushDeleteFiles(files, NavigationListFragmant.this))
                {
                    switchMode(Mode.normal, SelectMode.copy);
                }
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
            }
        });

        //View customTitleView = DialogUtils.buildCustomView(mActivity, R.string.CrushFileWarnning);
        //builder.setCustomTitle(customTitleView);
        builder.setTitle(R.string.CrushFileWarnning);
        AlertDialog dd = builder.create();
        dd.show();
                //DialogUtils.fromBottomToTop(dd);

    }

    private FileListener mListLocalListener;
    public boolean listLocalPath(FileListener l)
    {
        if(l == null)
            return false;

        mListLocalListener = l;
        switchMode(Mode.paste, SelectMode.download);
        return true;
    }
    LinkedList<File> buildSelectedFiles(String []fullpath)
    {
        LinkedList<File> ret = new LinkedList<File>();
        for(String name:fullpath)
        {
            File mFile = new File(name);
            if(mFile!=null)
                ret.add(mFile);
        }
        return ret;
    }
    public boolean listLocalPathPaste(FileListener l,Mode to,SelectMode from,String []fullpath)
    {
        if(l == null)
            return false;
        mSelectedFiles = buildSelectedFiles(fullpath);
        mListLocalListener = l;
        switchMode(to, from);
        return true;
    }

    public LinkedList<File> getSelectedFiles() { return (mMode == Mode.paste) ? mSelectedFiles : null; }
    public SelectMode getSelectedMode() { return mSelectMode; }
    public void setNormalMode(SelectMode from) { switchMode(Mode.normal, from); }

    private void showRenameDialog(final File file)
    {
        if(file.canWrite() == false)
        {
            //Cannt rename
            Toast.makeText(mActivity, R.string.RenameFail, Toast.LENGTH_SHORT).show();
            return;
        }

        LayoutInflater factory = LayoutInflater.from(mActivity);
        final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry_mkdir, null);
        final EditText editText = (EditText) textEntryView.findViewById(R.id.mkdir_edit);
        final String fileName = file.getName();
        editText.setText(fileName);
      //bug109831
        editText.requestFocus();
        editText.setSelection(0);
        // Let the selection shown at last.
        //editText.setSelection(TextUtils.isEmpty(fileName) ? 0 : fileName.length());

        final String dialogTitle = getString(R.string.dialog_title_rename, fileName);
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
        .setTitle(dialogTitle)
        .setView(textEntryView)
        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                String newname = editText.getText().toString();
                newname = newname.trim();
                if (newname.equalsIgnoreCase("")) {
                    showRenameDialog(file);
                } else {
                    String path = file.getPath();
                    String newFilename = path.substring(0, path.length() - file.getName().length())
                            + editText.getText().toString();
                    File mRenameTo = new File(newFilename);
                    if(mRenameTo.exists())
                    {
                        Toast.makeText(mActivity, R.string.RenameFileExist, Toast.LENGTH_SHORT).show();
                        //showRenameDialog(file);
                        return;
                    }

                    File mFile = new File(file.getAbsolutePath());
                    if (mFile.renameTo(mRenameTo) == false) {
                        Toast.makeText(mActivity, R.string.RenameFail, Toast.LENGTH_SHORT).show();
                    }
                    //Bugid:103592
                    CommonFunc.StartDeleteMediaFile();
                    CommonFunc.DeleteMediaFile(mRenameTo);
                    CommonFunc.EndDeleteMediaFile(mActivity,false);
                }
            }
        }).setNegativeButton(R.string.cancel, null);

        // For pop up the soft input window after dialog shown.
        Dialog dlg = builder.create();
        dlg.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        dlg.show();
    }

    private FileListener longClickFile = new FileListener()
    {
        @Override
        public void onFile(final File file)
        {
            if(mMode != Mode.normal)
            {
                return;
            }
            final int resArray = file.isDirectory() ? R.array.filemanager_folder_longpress_item
                    : R.array.filemanager_longpress_item;
            AlertDialog.Builder builder =  new AlertDialog.Builder(mActivity);
            builder.setItems(resArray, new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int which)
                {
                    String[] items = mActivity.getResources().getStringArray(resArray);
                    if(items[which].equalsIgnoreCase(mActivity.getResources().getString(R.string.actions_menu_rename)))
                    {
                        showRenameDialog(file);
                        CommonFunc.TA_Click(CommonFunc.LongPress_Rename);
                    }
                    else if(items[which].equalsIgnoreCase(mActivity.getResources().getString(R.string.actions_menu_Detail)))
                    {
                        //showDetail(file);
                        FileSystemObject fileObj = FileHelper.createFileSystemObject(file);
                        FileInfo PressFileInfo= new FileInfo(fileObj,0);
                        FileDetailDialog mFileDetailDialog = new FileDetailDialog(mActivity,
                                R.string.actions_menu_Detail,
                                PressFileInfo);
                        mFileDetailDialog.show(null);
                        CommonFunc.TA_Click(CommonFunc.LongPress_Detail);
                    }
                    else if(items[which].equalsIgnoreCase(mActivity.getResources().getString(R.string.actions_menu_Crush)))
                    {
                        if(file.canWrite() == true)
                        {
                            /*deleteUnrecovery(file);*/
                            FileSystemObject fileObj = FileHelper.createFileSystemObject(file);
                            FileInfo PressFileInfo= new FileInfo(fileObj,0);
                            final FileInfo PressFileInfoList[] = {PressFileInfo};
                            FileCrushDialog mFileCrushDialog = new FileCrushDialog(
                                                                    mActivity, PressFileInfoList);
                            mFileCrushDialog.show(null);
                            CommonFunc.TA_Click(CommonFunc.LongPress_Crush);
                        }
                    }
                    else if(items[which].equalsIgnoreCase(mActivity.getResources().getString(R.string.actions_menu_Copy)))
                    {
                        if(file.canRead() == false)
                        {
                            return;
                        }

                        LinkedList<File> files = new LinkedList<File>();
                        files.add(file);
                        mSelectedFiles = files;
                        switchMode(Mode.paste, SelectMode.copy);
                        CommonFunc.TA_Click(CommonFunc.LongPress_Copy);
                    }
                    else if(items[which].equalsIgnoreCase(mActivity.getResources().getString(R.string.actions_menu_Cut)))
                    {
                        if(file.canRead() == false || file.canWrite() == false)
                        {
                            return;
                        }
                        LinkedList<File> files = new LinkedList<File>();
                        files.add(file);
                        mSelectedFiles = files;
                        switchMode(Mode.paste, SelectMode.cut);
                        CommonFunc.TA_Click(CommonFunc.LongPress_Cut);
                    }
                    else if(items[which].equalsIgnoreCase(mActivity.getResources().getString(R.string.actions_menu_delete)))
                    {
                        if(file.canWrite() == false)
                        {
                            return;
                        }
                        LinkedList<File> files = new LinkedList<File>();
                        files.add(file);
                        deleteFiles(files);
                        CommonFunc.TA_Click(CommonFunc.LongPress_Delete);
                    }
                    else if(items[which].equalsIgnoreCase(mActivity.getResources().getString(R.string.actions_menu_Share)))
                    {

                        LinkedList<File> files = new LinkedList<File>();
                        files.add(file);
                        CommonFunc.shareDialog(mActivity, files);
                        CommonFunc.TA_Click(CommonFunc.LongPress_Share);
                    }
                    else if(items[which].equalsIgnoreCase(mActivity.getResources().getString(R.string.actions_menu_Zip)))
                    {
                        Log.v("rwei", "actions_menu_Zip");
                        LinkedList<File> files = new LinkedList<File>();
                        files.add(file);
                        ZipDialog mZipDialog = new ZipDialog(mActivity, files,file.getParentFile().getPath());
                        mZipDialog.show();
                        //CommonFunc.TA_Click(CommonFunc.LongPress_Share);
                    }
                    dialog.dismiss();//rwei
                }
            });

            builder.setNegativeButton(R.string.cancel, null);
            Dialog dd = builder.create();
            dd.show();
                        //DialogUtils.fromBottomToTop(dd);

        }
    };

    @Override
    public void onChanged()
    {
        if(mMode == Mode.normal || mMode == Mode.search)
        {
            boolean hasFile = (fm.getFiles().length != 0);
            File currentDir = fm.getCurrentDir();
            boolean canRead = currentDir != null ? currentDir.canRead() : false;
            boolean canWrite = currentDir != null ? currentDir.canWrite() : false;
            //mFooterBarMenu.getItem(MENU_ID_ORDER).setEnabled(hasFile);
            mFooterBarMenu.setItemEnable(MENU_ID_ORDER, hasFile);
            //mFooterBarMenu.getItem(MENU_ID_COPY).setEnabled(canRead && hasFile);
            mFooterBarMenu.setItemEnable(MENU_ID_COPY, canRead && hasFile);
            //mFooterBarMenu.getItem(MENU_ID_DELETE).setEnabled(canRead && canWrite && hasFile);
            mFooterBarMenu.setItemEnable(MENU_ID_DELETE, canRead && canWrite && hasFile);
            //mFooterBarMenu.getItem(MENU_ID_CUT).setEnabled(canRead && canWrite && hasFile);
            mFooterBarMenu.setItemEnable(MENU_ID_CUT, canRead && canWrite && hasFile);
            //mFooterBarMenu.getItem(MENU_ID_SHARE).setEnabled(canRead && hasFile);
            mFooterBarMenu.setItemEnable(MENU_ID_SHARE, canRead && hasFile);
            //mFooterBarMenu.getItem(MENU_ID_NEWFOLDER).setEnabled(canRead && canWrite);
            mFooterBarMenu.setItemEnable(MENU_ID_NEWFOLDER, canRead && canWrite);
            //mFooterBarMenu.setItemEnable(MENU_ID_ORDER, hasFile);
            mFooterBarMenu.setItemEnable(MENU_ID_ORDER, hasFile);
            mFooterBarMenu.setItemEnable(MENU_ID_ZIP, hasFile);

        }
        else if(mMode == Mode.paste)
        {
            File currentDir = fm.getCurrentDir();
            boolean canWrite = currentDir != null ? currentDir.canWrite() : false;
            //mFooterBarButton.getItem(MENU_ID_SELECT).setEnabled(canWrite);
            //BugID:104438:disable download button when can't write
            mFooterBarButton.setItemEnable(MENU_ID_SELECT, canWrite);
            if (canWrite) {
                mFooterBarButton.setItemTextColor(MENU_ID_SELECT, mActivity.getResources().getColor(R.color.button_text_color_ok));
            }else {
                mFooterBarButton.setItemTextColor(MENU_ID_SELECT, Color.GRAY);
            }
        }else if (mMode == Mode.select ) {
            //when there is no select,the button should be Color.GRAY
            LinkedList<File> files = mAdapter.getSelectedFiles();
            if(files == null || files.size() == 0)
            {
                mFooterBarButton.setItemTextColor(MENU_ID_SELECT, Color.GRAY);
                return;
            }
        }

        mFooterBarMenu.setVisibility(fm.isCurrentRoot() ? View.INVISIBLE : View.VISIBLE);

        updateTopTag();
    }

    private View getTagView(String tag, String folderPath)
    {
        ViewGroup v = (LinearLayout)LayoutInflater.from(mActivity).inflate(R.layout.crumbs_item, null);
        v.setBackgroundResource(R.drawable.aui_crumb_bg_sub);
        v.setClickable(true);
        ((TextView)v.findViewById(R.id.dir_name)).setText(tag);

        final File folder = new File(folderPath);
        v.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if((mMode == Mode.search)||(mMode == Mode.select))
                {
                    if(mMode == Mode.search)
                        mWidgetSearchView.clearFocus();
                    switchMode(Mode.normal, SelectMode.copy);
                }
                fm.openFolder(folder);
            }
        });
        return v;
    }

    private void updateTopTag()
    {
        mDirContainer.removeAllViews();

        LinearLayout ItemMain = (LinearLayout) LayoutInflater.from(mActivity).inflate(
                R.layout.crumbs_item, null);
        ItemMain.setBackgroundResource(R.drawable.aui_crumb_bg_main);
        ItemMain.setClickable(true);
        TextView titleMain = (TextView) ItemMain.findViewById(R.id.dir_name);
        titleMain.setText(mActivity.getString(R.string.AllFiles));
        mDirContainer.addView(ItemMain);
        ItemMain.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if((mMode == Mode.search) || (mMode == Mode.select)) {
                    if(mMode == Mode.search)
                        mWidgetSearchView.clearFocus();
                    switchMode(Mode.normal, SelectMode.copy);
                }
                fm.goRootFolder();
            }
        });

        String rootName = fm.getRootName();
        String rootPath = fm.getRootPath();
        String currentDir = fm.getCurrentDir().getAbsolutePath();
        LinearLayout.LayoutParams margin = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        margin.setMargins((int)(-1*AndroidHelper.convertDpToPixel(mActivity, 10)), 0, 0, 0);

        if(currentDir.startsWith(rootPath))
        {
            String path = currentDir.substring(rootPath.length());
            String[] tags = path.split(File.separator);

            if(rootName != null && rootName.length() > 0)
            {
                mDirContainer.addView(getTagView(rootName, rootPath),margin);
            }

            for(String tag : tags)
            {
                if(tag == null || tag.length() <= 0)
                {
                    continue;
                }
                rootPath += File.separator + tag;
                mDirContainer.addView(getTagView(tag, rootPath),margin);
            }
        }
        else
        {
            fm.goUpFolder();
        }
        mHandler.removeCallbacks(mTagScrollRun);
        mHandler.post(mTagScrollRun);
    }
    private Runnable mTagScrollRun = new Runnable(){ @Override public void run()
    {
        if(mTagScroll != null)
        {
            mTagScroll.fullScroll(View.FOCUS_RIGHT);
        }
    }};

    @Override public boolean setLoginStatus(boolean status) { return false; }
    @Override public boolean judgeUpload() { return false; }
    @Override
    public boolean setMobileFlag() {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public void onProgress(File f,long currentbytes, long totalbytes) {
        // TODO Auto-generated method stub
		if (mProgressDialog != null || mProgressDialog.isShowing()) {
			mProgressDialog.setMax((int) (totalbytes / SIZE));
			mProgressDialog.setProgress((int) (currentbytes / SIZE));
			mProgressDialog.setMessage(f.getAbsolutePath());
        }
    }
}
